package com.peanut.baby.mvp.main.expert.qa;

import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import androidx.annotation.Nullable;
import androidx.viewpager.widget.ViewPager;

import com.peanut.baby.InitManager;
import com.peanut.baby.R;
import com.peanut.baby.comm.MyViewPagerAdapter;
import com.peanut.baby.model.Ad;
import com.peanut.baby.model.QA;
import com.peanut.baby.mvp.BaseMvpFragment;
import com.peanut.baby.mvp.bind.BindMobileActivity;
import com.peanut.baby.mvp.login.LoginActivity;
import com.peanut.baby.mvp.qadetail.QADetailActivity;
import com.peanut.baby.mvp.web.WebViewActivity;
import com.peanut.devlibrary.imageloader.ImageLoader;
import com.peanut.devlibrary.util.StringUtil;
import com.peanut.devlibrary.widget.pullrecycle.PullRecyclerView;
import com.peanut.devlibrary.widget.pullrecycle.layoutmanager.XLinearLayoutManager;
import com.tencent.mars.xlog.Log;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * Created by anonymouslystudio on 2017/7/12.
 */

public class MainQaFragment extends BaseMvpFragment implements PullRecyclerView.OnRecyclerRefreshListener,
    QARecyclerAdapter.OnItemViewClickListener,
    MainQaContract.View, ViewPager.OnPageChangeListener{

    private static final String TAG = MainQaFragment.class.getSimpleName();
    @BindView(R.id.pull_recycler)
    PullRecyclerView pullRecyclerView;
    @BindView(R.id.banner_viewpager)
    ViewPager bannerViewpager;
    @BindView(R.id.banner_radiogroup)
    RadioGroup  bannerRadiogroup;
    @BindView(R.id.banner_frame)
    FrameLayout bannerFrame;

    Unbinder unbinder;

    private int pageNo  = 1;
    private int pageCount = 5;


    protected MyViewPagerAdapter mAdAdapter;                      //banner适配器
    protected List<View> mAdViews;
    private Runnable scrollRunnable;
    private boolean resumed = false;
    private Handler handler = new Handler();


    private QARecyclerAdapter adapter;
    private List<QA>  qas;
    private MainQaPresenter presenter;


    public static MainQaFragment newInstance() {
        return new MainQaFragment();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_expert_qa, null);
        unbinder = ButterKnife.bind(this, rootView);


        return rootView;
    }

    @Override
    public void initData() {
        presenter = new MainQaPresenter(this,getActivity());

        scrollRunnable = new Runnable() {
            @Override
            public void run() {
                if (mAdAdapter != null && mAdAdapter.getCount() > 0) {
                    int currentIndex = bannerViewpager.getCurrentItem();
                    int pos = currentIndex + 1;
                    if (pos > mAdAdapter.getCount() - 1) {
                        pos = 0;
                    }

                    bannerViewpager.setCurrentItem(pos);
                }
                if (resumed) {
                    handler.postDelayed(scrollRunnable, 3000);
                }
            }
        };


        qas = new ArrayList<>();
        adapter = new QARecyclerAdapter(getActivity(),qas);
//        View header = LayoutInflater.from(getActivity()).inflate(R.layout.layout_banner,null);
//        bannerFrame = (FrameLayout) header.findViewById(R.id.banner_frame);
//        bannerViewpager = (ViewPager) header.findViewById(R.id.banner_viewpager);
//        bannerRadiogroup = (RadioGroup) header.findViewById(R.id.banner_radiogroup);
        fixBannerSize();

        pullRecyclerView.setLayoutManager(new XLinearLayoutManager(getActivity()));
        pullRecyclerView.setAdapter(adapter);
//        pullRecyclerView.addHeaderView(header);

        pullRecyclerView.enablePullRefresh(true);
        pullRecyclerView.enableLoadMore(true);
        pullRecyclerView.setOnRecyclerRefreshListener(this);

        adapter.setOnClickListener(this);
        pullRecyclerView.postRefreshing();


    }

    private void fixBannerSize(){
        //
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) bannerFrame.getLayoutParams();
        params.height = InitManager.getInstance().getScreenWidth() * 3 / 5;
        bannerFrame.setLayoutParams(params);
    }

    private void fakeHideBanner(){
        //
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) bannerFrame.getLayoutParams();
        params.height = 1;
        bannerFrame.setLayoutParams(params);
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }


    @Override
    public void onPullRefresh() {
        presenter.getBanner();
        pageNo = 1;
        presenter.getQAList(pageNo,pageCount);
    }

    @Override
    public void onLoadMore() {
        pageNo += 1;
        presenter.getQAList(pageNo,pageCount);
    }

    @Override
    public void onViewItemClicked(View v, QA item) {
        QADetailActivity.start(getActivity(),item.id);
    }

    @Override
    public void onViewPraiseClicked(QA qa) {
        if(InitManager.getInstance().getUser() == null){
            LoginActivity.startForResult(getActivity());
            return;
        }
        if(StringUtil.isNullOrEmpty(InitManager.getInstance().getUser().userToken)){
            BindMobileActivity.startForResult(getActivity());
            return;
        }
        presenter.praiseQA(qa);
    }

    @Override
    public void onGetQAListSuccess(List<QA> _qas) {
        Log.d(TAG,"onGetQAListSuccess: result "+(_qas == null? "null":""+_qas.size()));
        stopRefreshAndLoad();
        if(_qas != null && !_qas.isEmpty()){
            if(pageNo == 1){
                qas.clear();
            }
            qas.addAll(_qas);
            adapter.notifyDataSetChanged();
            pullRecyclerView.enableLoadMore(_qas.size() >= pageCount); // 当剩余还有大于0页的数据时，开启上拉加载更多
        }
    }

    @Override
    public void onRequestFailed(String reason) {
        stopRefreshAndLoad();
        showToast(reason);

    }

    @Override
    public void onResume() {
        super.onResume();
        resumed = true;
        handler.postDelayed(scrollRunnable, 3000);

    }

    @Override
    public void onPause() {
        super.onPause();
        resumed = false;
        handler.removeCallbacks(scrollRunnable);


    }

    @Override
    public void onPraiseSuccess(QA qa) {
        adapter.notifyDataSetChanged();
    }

    @Override
    public void onPraiseFailed(String reason) {
        adapter.notifyDataSetChanged();
        showToast(reason);
    }

    @Override
    public void onBannerGet(boolean success, List<Ad> ads, String failReason) {
        initBanners(ads);
    }

    private void initBanners(final List<Ad> objs) {
        if (getActivity() != null) {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (objs == null || objs.isEmpty()) {
                        fakeHideBanner();
                        return;
                    }
                    fixBannerSize();
                    if (mAdViews == null) {
                        mAdViews = new ArrayList<View>();
                    }
                    mAdViews.clear();
                    bannerRadiogroup.removeAllViews();
                    int size = objs.size();
                    int rightMargin = getActivity().getResources().getDimensionPixelSize(R.dimen.ad_radio_size);
                    for (int i = 0; i < size; i++) {
                        final Ad ad = objs.get(i);
                        final View adView = getActivity().getLayoutInflater().inflate(R.layout.layout_ad, null);
                        final ImageView img = (ImageView) adView.findViewById(R.id.ad_image);

                        ImageLoader.getInstance().loadImageView(getActivity(), ad.imgUrl, img);


                        mAdViews.add(adView);

                        adView.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                WebViewActivity.start(getActivity(), ad.htmlUrl, ad.name,ad.imgUrl);
                            }
                        });

                        RadioButton radioButton = new RadioButton(getActivity());
                        radioButton.setButtonDrawable(new ColorDrawable(Color.TRANSPARENT));
                        try {
                            radioButton.setBackgroundDrawable(getActivity().getResources().getDrawable(R.drawable.selector_ad_radiobutton));
                        } catch (Resources.NotFoundException e) {
                            e.printStackTrace();
                        }
                        RadioGroup.LayoutParams params = new RadioGroup.LayoutParams(rightMargin, rightMargin);
                        if (i != (size - 1)) {
                            params.rightMargin = rightMargin;
                        }
                        bannerRadiogroup.addView(radioButton, params);


                    }
                    ((RadioButton) bannerRadiogroup.getChildAt(0)).setChecked(true);
                    mAdAdapter = new MyViewPagerAdapter(mAdViews);
                    bannerViewpager.setAdapter(mAdAdapter);
                    bannerViewpager.setOnPageChangeListener(MainQaFragment.this);

                }
            });
        }
    }

    private void stopRefreshAndLoad(){
        pullRecyclerView.stopRefresh();
        pullRecyclerView.stopLoadMore();
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        ((RadioButton) bannerRadiogroup.getChildAt(position)).setChecked(true);
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }
}
